<template>
  <Layout>
    <div class="permission-management max-width-1500">
      <div class="header">
        <h2>权限管理</h2>
        <div class="header-actions">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索用户账号或名称"
            style="width: 200px; margin-right: 10px;"
            clearable
            @clear="fetchUserList"
            @keydown.enter="fetchUserList"
          >
            <template #append>
              <el-button :icon="Search" @click="fetchUserList" />
            </template>
          </el-input>
          <el-button type="primary" @click="savePermissions" :disabled="!selectedUserId || !permissionData">
            保存权限
          </el-button>
          <el-button type="success" @click="fetchUserList" :loading="loading">
            刷新
          </el-button>
        </div>
      </div>

      <div class="container">
        <!-- 用户列表 -->
        <div class="user-list-container">
          <el-table
            ref="userTableRef"
            :data="filteredUserList"
            style="width: 100%"
            v-loading="loading"
            element-loading-text="加载中..."
            highlight-current-row
            :current-row-key="selectedUserId"
            @current-change="handleUserSelect"
          >
            <el-table-column label="头像" width="60">
              <template #default="scope">
                <el-avatar 
                  :size="30" 
                  :src="scope.row.avatar"
                >
                  {{ scope.row.name?.charAt(0) }}
                </el-avatar>
              </template>
            </el-table-column>
            <el-table-column prop="account" label="账号"/>
            <el-table-column prop="name" label="名称"/>
            <el-table-column prop="role" label="角色" width="80">
              <template #default="scope">
                <el-tag v-if="scope.row.role === 'admin'">管理员</el-tag>
                <el-tag type="info" v-else>普通用户</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 权限详情 -->
        <div class="permissions-container">
          <div v-if="permissionData" class="permissions-content">
            <div class="permission-category" v-for="(category, categoryKey) in permissionData" :key="categoryKey">
              <div class="category-header">
                <div class="category-title">{{ category.name }}</div>
                <div class="category-controls">
                  <el-checkbox
                    v-model="permissionData[categoryKey].pageShow"
                    label="页面显示"
                    :disabled="category.pageShowDisable"
                  />
                </div>
                <div class="category-permissions">
                  <div
                    v-for="(permission, permissionKey) in category.permissions"
                    :key="permissionKey"
                    class="permission-item"
                  >
                    <el-checkbox
                      v-model="permissionData[categoryKey].permissions[permissionKey].value"
                      :label="permission.name"
                      :disabled="permission.disable"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <div v-else-if="loadingPermissions" class="loading-container">
            <el-skeleton animated />
          </div>
          
          <div v-else class="empty-container">
            <el-empty description="请选择用户以查看和管理权限" />
          </div>
        </div>
      </div>
    </div>
  </Layout>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, nextTick, watch } from 'vue';
import type { ElTable } from 'element-plus';
import { ElMessage } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import Layout from '@/components/Layout.vue';
import { getUserList } from '@/api/modules/user';
import { getUserPermissions, updateUserPermissions, type GetUserPermissionResult, type UpdateUserPermissionData } from '@/api/modules/permission';

interface User {
  user_id: number;
  account: string;
  name: string;
  avatar?: string;
  role?: string;
}

const userTableRef = ref<InstanceType<typeof ElTable> | null>(null);
const userList = ref<User[]>([]);
const selectedUser = ref<User | null>(null);
const selectedUserId = ref<number | null>(null);
const permissionData = ref<GetUserPermissionResult['permissions'] | null>(null);
const originalPermissionData = ref<GetUserPermissionResult['permissions'] | null>(null);
const loading = ref(false);
const loadingPermissions = ref(false);
const searchKeyword = ref('');

// 根据搜索关键词过滤用户列表
const filteredUserList = computed(() => {
  if (!searchKeyword.value) {
    return userList.value;
  }
  
  const keyword = searchKeyword.value.toLowerCase();
  return userList.value.filter(user => 
    user.account.toLowerCase().includes(keyword) || 
    user.name.toLowerCase().includes(keyword)
  );
});

// 监听用户列表变化，如果当前没有选中用户且列表不为空，则选中第一个
watch(userList, (newUserList) => {
  if (newUserList.length > 0 && !selectedUser.value) {
    // 使用 setTimeout 确保在 DOM 更新完成后执行
    setTimeout(() => {
      handleUserSelect(newUserList[0]);
      // 手动设置表格当前行
      userTableRef.value?.setCurrentRow(newUserList[0]);
    }, 0);
  }
});

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true;
  try {
    const response = await getUserList();
    userList.value = response.data || [];
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 处理用户选择
const handleUserSelect = async (user: User | null) => {
  selectedUser.value = user;
  selectedUserId.value = user?.user_id || null;
  
  if (!user) {
    permissionData.value = null;
    return;
  }
  
  loadUserPermissions(user.user_id);
};

// 加载用户权限
const loadUserPermissions = async (userId: number) => {
  loadingPermissions.value = true;
  try {
    const res = await getUserPermissions(userId);
    // 深拷贝权限数据，一份用于显示，一份用于比较是否有修改
    permissionData.value = JSON.parse(JSON.stringify(res.data.permissions));
    originalPermissionData.value = JSON.parse(JSON.stringify(res.data.permissions));
  } catch (error) {
    console.error(error);
    permissionData.value = null;
  } finally {
    loadingPermissions.value = false;
  }
};

// 保存权限设置
const savePermissions = async () => {
  if (!selectedUserId.value || !permissionData.value) {
    ElMessage.warning('请先选择用户');
    return;
  }

  // 检查是否有修改
  if (JSON.stringify(permissionData.value) === JSON.stringify(originalPermissionData.value)) {
    ElMessage.info('权限未发生更改');
    return;
  }

  try {
    const payload: UpdateUserPermissionData = {
      user_id: selectedUserId.value,
      permissions: permissionData.value
    };

    await updateUserPermissions(payload);
    ElMessage.success('权限保存成功');
    // 更新原始数据
    originalPermissionData.value = JSON.parse(JSON.stringify(permissionData.value));
  } catch (error) {
    console.error(error);
  }
};

onMounted(() => {
  fetchUserList();
});
</script>

<style scoped>
.permission-management {
  padding: 20px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  height: 100%;
  overflow: auto;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  align-items: center;
}

.container {
  display: flex;
  flex: 1;
  overflow: auto;
}

.user-list-container {
  width: 30%;
  display: flex;
  flex-direction: column;
  border-right: 1px solid #ebeef5;
  padding-right: 20px;
}

.permissions-container {
  width: 70%;
  padding-left: 20px;
  display: flex;
  flex-direction: column;
}

.permissions-content {
  flex: 1;
  overflow: auto;
}

.permission-category {
  margin-bottom: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 8px;
}

.permission-category:last-child {
  margin-bottom: 0;
}

.category-header {
  display: flex;
}

.category-title {
  width: 150px;
  font-weight: bold;
  font-size: 16px;
  padding-right: 15px;
  border-right: 1px solid #ebeef5;
  display: flex;
  align-items: center;
}

.category-controls {
  width: 100px;
  padding: 0 10px;
  border-right: 1px solid #ebeef5;
  display: flex;
  align-items: center;
}

.category-permissions {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 6px;
  padding-left: 15px;
}

.permission-item {
  display: flex;
  align-items: center;
}

.loading-container,
.empty-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>